package com.newenergy.wisehome.gateway.device;


import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.manager.MyThreadManager;
import com.newenergy.wisehome.gateway.adapter.DnaDeviceAdapter;
import com.newenergy.wisehome.gateway.common.BLCommonUtils;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.fragment.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.com.broadlink.family.BLFamily;
import cn.com.broadlink.family.params.BLFamilyAllInfo;
import cn.com.broadlink.family.params.BLFamilyDeviceInfo;
import cn.com.broadlink.family.params.BLFamilyInfo;
import cn.com.broadlink.family.params.BLFamilyModuleInfo;
import cn.com.broadlink.family.result.BLAllFamilyInfoResult;
import cn.com.broadlink.family.result.BLModuleControlResult;
import cn.com.broadlink.sdk.BLLet;
import cn.com.broadlink.sdk.data.controller.BLDNADevice;

/**
 * A simple {@link Fragment} subclass.
 */
public class FamilyBLDeviceFragment extends BaseFragment {

    @BindView(R.id.btn_refresh_device)
    Button mBtnRefreshDevice;
    @BindView(R.id.btn_update_device)
    Button mBtnUpdateDevice;
    Unbinder unbinder;
    private ArrayList<BLDNADevice> mData;
    private DnaDeviceAdapter mAdapter;


    @BindView(R.id.rv_bl_device)
    RecyclerView mRecyclerView;
    private String mBlFamilyId;
    private BLDNADevice mLocalDevice;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Override
    public int getLayoutId() {
        return R.layout.fragment_family_bldevice;
    }

    @Override
    public void init(View rootView) {
        mData = new ArrayList<BLDNADevice>();
        initRecyclerView();
        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
        mBlFamilyId = familyManager.mBLFamilyId;
        mLocalDevice = familyManager.mLocalDnaDevice;
        getBLFamilyDevices();
    }

    private void initRecyclerView() {
        mAdapter = new DnaDeviceAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

    }


    @Override
    public void onResume() {
        super.onResume();
//        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
//        List<BLFamilyDeviceInfo> blFamilyDevices = familyManager.getCurrBLFamilyDevices();
//        if (blFamilyDevices.size() > 0) {
//            for (BLFamilyDeviceInfo familyDevice : blFamilyDevices) {
//                BLDNADevice bldnaDevice = familyManager.familyDeviceToDnaDevice(familyDevice);
//                mAdapter.addData(bldnaDevice);
//            }
//        }
    }

    @OnClick({R.id.btn_refresh_device, R.id.btn_update_device})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_refresh_device:
                getBLFamilyDevices();
                break;
            case R.id.btn_update_device:
                break;
        }
    }

    public void getBLFamilyDevices() {
        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
        mBlFamilyId = familyManager.mBLFamilyId;
        boolean checkNetwork = BLCommonUtils.checkNetwork(getContext());
        if (!checkNetwork) {
            toast("没网络");
            return;
        }
        if (TextUtils.isEmpty(mBlFamilyId)) {
            toast("家庭码为空");
            return;
        }
        MyThreadManager.getInstance().doTask(() -> {
            queryBLFamilyDeviceTask();
        });
    }


    private void queryBLFamilyDeviceTask() {
        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
        String[] blFamilyIds = {mBlFamilyId};
        mData.clear();
        mAdapter.clear();
        BLAllFamilyInfoResult allFamilyInfos = BLFamily.queryAllFamilyInfos(blFamilyIds);

        List<BLFamilyAllInfo> allInfos = allFamilyInfos.getAllInfos();
        if (allInfos != null && allInfos.size() > 0) {
            BLFamilyAllInfo familyAllInfo = allInfos.get(0);
            List<BLFamilyDeviceInfo> deviceInfos = familyAllInfo.getDeviceInfos();
            if (deviceInfos != null && deviceInfos.size() > 0) {
                for (BLFamilyDeviceInfo familyDevice : deviceInfos) {
                    BLDNADevice bldnaDevice = familyManager.familyDeviceToDnaDevice(familyDevice);
                    BLLet.Controller.addDevice(bldnaDevice);
//                    Log.i(TAG, "queryBLFamilyDeviceTask: bldnaDevice = " + bldnaDevice.toJSONString());
                    Log.i(TAG, "BLFamilyDeviceInfo: "+familyDevice.toDictionary().toString());
                    mData.add(bldnaDevice);
                }
            }
        }
        mHandler.post(() -> {
            mAdapter.addAll(mData);
//            mAdapter.notifyDataSetChanged();
        });
    }

    private class UpdateBLFamilyDeviceTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
            String[] blFamilyIds = {mBlFamilyId};
            mData.clear();
            BLAllFamilyInfoResult allFamilyInfos = BLFamily.queryAllFamilyInfos(blFamilyIds);

            List<BLFamilyAllInfo> allInfos = allFamilyInfos.getAllInfos();
            if (allInfos != null && allInfos.size() > 0) {
                BLFamilyAllInfo familyAllInfo = allInfos.get(0);
                BLFamilyInfo familyInfo = familyAllInfo.getFamilyInfo();
                List<BLFamilyDeviceInfo> deviceInfos = familyAllInfo.getDeviceInfos();
                List<BLFamilyModuleInfo> moduleInfos = familyAllInfo.getModuleInfos();

                if (deviceInfos != null && deviceInfos.size() > 0) {
                    BLFamilyDeviceInfo deviceInfo = deviceInfos.get(0);
                    BLFamilyModuleInfo moduleInfo = moduleInfos.get(0);
                    deviceInfo.setAeskey(mLocalDevice.getKey());
                    BLModuleControlResult result = BLFamily.addModuleToFamily(moduleInfo, familyInfo, deviceInfo, null);
                    if (result != null && result.succeed()) {
                        Log.i(TAG, "更新模块key成功: ");
                    } else if (result != null && !result.succeed()) {
                        Log.e(TAG, "更新模块key失败: error = " + result.getError() + ", msg = " + result.getMsg());
                    }

//                for (BLFamilyDeviceInfo familyDevice : deviceInfos) {
//                    BLDNADevice bldnaDevice = familyManager.familyDeviceToDnaDevice(familyDevice);
//                    mData.add(bldnaDevice);
//                }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mAdapter.notifyDataSetChanged();
        }
    }


}
